﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ModbusTestTool.Error_Logging
{
    /// <summary>
    /// This is a singleton class that will allow error logging through the entire porgram
    /// </summary>
    public class ErrorLog
    {
        static ErrorLog _instance = new ErrorLog();
        List<ErrorLogMessage> log = new List<ErrorLogMessage>();
        Object lockVar = new object();

        public delegate void handleError();
        public handleError errorHandler;


        public class ErrorLogMessage {
            public DateTime time { set; get; }
            public string message { set; get; }
        }


        private ErrorLog()
        {
        }

        public void addMessage(string message)
        {
            lock (lockVar)
            {
                log.Add(new ErrorLogMessage(){time=DateTime.Now,message = message});
  
            }


            //This must be done outside the lock otherwise you will end up with a lock condition
            if (errorHandler != null)
            {
                errorHandler();
            }
        }

        public ErrorLogMessage getMessage()
        {
            lock (lockVar)
            {
                if (log.Count != 0)
                {
                    ErrorLogMessage message = log.First();
                    log.RemoveAt(0);
                    return message;
                }
                else
                {
                    return null;
                }

            }
        }

        public static ErrorLog Instance
        {
            get
            {
                return _instance;
            }
        }
    }
}
